package com.zkx.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.zkx.common.exception.APIException;
import com.zkx.common.result.ResultCode;

import java.util.Calendar;
import java.util.Map;

//JWT工具类
public class JWTUtils {

    private static final String SIGN = "!Q0_#JD^,O";
    /**
     * 生成token  header.payload.signature
     */
    public static String getToken(Map<String,String> map){
        //Calendar 日历类
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE,60);//60分钟过期
        //创建JWT builder
        JWTCreator.Builder builder = JWT.create();

        //header 系统默认添加
        //payload
        map.forEach((k,v) ->{
            builder.withClaim(k,v);
        });
        //指定令牌过期时间 和 signature
        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SIGN));
        return token;
    }
    /**
     *
     * 验证token 合法性
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }
    /**
     * 获取token信息方法
     */
    public static String getTokenInfo(String token){
        try{
            return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token).getToken();
        }
        catch (SignatureVerificationException e){
            throw new APIException(ResultCode.SIGNATURE_INVALID);
        }
        catch (TokenExpiredException e){
            throw new APIException(ResultCode.TOKEN_EXPIRED);
        }
        catch (AlgorithmMismatchException e){
            throw new APIException(ResultCode.TOKEN_ALGORITHM_INCONSISTENT);
        }
        catch (Exception e){
            throw new APIException(ResultCode.TOKEN_EMPTY);
        }
    }

}
